<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/10/19 10:10
 * Modified Time: 2019/10/19 10:10
 * Version: 2.0
 */

namespace App\Modules\Order\Criterias;


use Flower\Core\Repository\Contracts\RepositoryInterface;
use Flower\Core\Repository\Criterias\BaseCriterias;

class GetAppointmentAppCriteria extends BaseCriterias
{
	protected $store_id;
	protected $is_barber;
	protected $user_id;
	protected $status;
	protected $source;
	protected $keywords;
	protected $is_pad;
	protected $orderIds;

	public function __construct($store_id, $is_barber, $user_id, $status, $source, $keywords, $orderIds = [])
	{
		$this->store_id = $store_id;
		$this->is_barber = $is_barber;
		$this->user_id = $user_id;
		$this->status = $status;
		$this->source = $source;
		$this->keywords = $keywords;
		$this->orderIds = $orderIds;
	}

	public function apply($model, RepositoryInterface $repository)
	{
		$store_id = $this->store_id;
		$is_barber = $this->is_barber;
		$user_id = $this->user_id;
		$status = $this->status;
		$source = $this->source;
		$keywords = $this->keywords;
		$orderIds = $this->orderIds;
		return $model
			->with([
				'user' => function ($query) {
					$query->with('picture:id,image')->select(['id', 'username', 'portrait']);
				}
			])
			->with([
				'service' => function ($k) {
					$k->select(['id', 'name', 'type'])->with([
						'category' => function ($sv) {
							$sv->select(['id', 'code', 'fullname', 'resource'])->with([
								'picture' => function ($v) {
									$v->select(['id', 'image']);
								}
							]);
						}
					]);
				}
			])
			->where('store_id', $store_id)
			->when(!empty($orderIds), function ($query) use ($orderIds) {
				$query->whereIn('id', $orderIds);
			})
			->when($is_barber, function ($query) use ($user_id) {
				$query->where('barber_id', $user_id);
			})
			->when(isset($status), function ($query) use ($status) {
				$query->where('status', $status);
			})
			->when(!empty($source), function ($query) use ($source) {
				$query->where('source', $source);
			})
			->when(!empty($keywords), function ($query) use ($keywords) {
				$query->where('nick', 'like', '%' . $keywords . '%')
					->orWhere('mobile', 'like', '%' . $keywords . '%');
			})
			->orderBy('created_at');
	}
}